package com.woniuxy.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.zsd.commons.core.exception.ZsdException;
import com.woniu.zsd.commons.core.model.Result;
import com.woniuxy.user.entity.UserAddresses;
import com.woniuxy.user.mapper.UserAddressesMapper;
import com.woniuxy.user.mapper.UserInfoMapper;
import com.woniuxy.user.mapper.UserLogMapper;
import com.woniuxy.user.param.AddAddressesParam;
import com.woniuxy.user.service.IUserAddressesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.user.service.IUserLogService;
import com.woniuxy.user.utils.GaoDeMapUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户地址表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-13
 */
@Service
public class  UserAddressesServiceImpl extends ServiceImpl<UserAddressesMapper, UserAddresses> implements IUserAddressesService {
        @Resource
        private UserAddressesMapper userAddressesMapper;

        @Resource
        private UserInfoMapper userInfoMapper;
        @Resource
        private IUserLogService userLogService;
    @Resource
    private UserLogMapper userLogMapper;


    @Override
    public Result<String> addAddresses(AddAddressesParam param) throws Exception {
        // 调用高德地图API获取经纬度
        String address = param.getAddresses();
        String latLon = GaoDeMapUtil.getLonLat(address);
        if (latLon == null) {
            System.out.println("经纬度获取失败");
        }
            //  把经纬度塞入user_addresses表的longitude和latitude字段
        String[] latLonArray = latLon.split(",");
        param.setLatitude(Double.parseDouble(latLonArray[0]));
        param.setLongitude(Double.parseDouble(latLonArray[1]));
        System.out.println("用户输入地址的经纬度：" + latLon);
        System.out.println("经纬度：" + latLonArray[0] + "," + latLonArray[1]);
        System.out.println("用户id1594641523456"+param.getUserId());
        //如果地址信息一样并且经纬度一样就提示用户地址已存在
        if (userAddressesMapper.selectCount(new QueryWrapper<UserAddresses>().eq("addresses", address)) > 0) {
            userLogService.logDeleteAddressAction(String.valueOf(param.getUserId()), "地址已存在", 0, "地址已存在");
            throw new ZsdException("地址已存在", 1010);
        }
        //如果拥有的地址超过10条就提示用户地址已满
        if (userAddressesMapper.selectCount(new QueryWrapper<UserAddresses>().eq("user_id", param.getUserId())) >= 10) {
            throw new ZsdException("地址已满,请删除一条部分再添加", 1010);
        }

        param.setUserId(Integer.parseInt(String.valueOf(param.getUserId())));
        //把地址信息塞入user_addresses表以及userId
        UserAddresses userAddresses = new UserAddresses();
        BeanUtils.copyProperties(param, userAddresses);
        userAddressesMapper.insert(userAddresses);



        return null;
    }

    @Override
    public List<UserAddresses> getAllAddresses(String userId) throws Exception {
        // 查询 user_addresses 表中该用户的所有地址信息
        QueryWrapper<UserAddresses> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<UserAddresses> addressesList = userAddressesMapper.selectList(queryWrapper);
        return addressesList;
    }


    @Override
    public boolean deleteAddresses(String userId, int id) throws Exception {
        // 判断是否是自己的地址
        QueryWrapper<UserAddresses> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("id", id);
        int count = Math.toIntExact(userAddressesMapper.selectCount(queryWrapper));
        if (count == 0) {
            userLogService.logDeleteAddressAction(userId, "不是自己的地址不能删除", 0, "不是自己的地址不能删除");
            throw new ZsdException("不是自己的地址不能删除", 1011);
        }

        // 检查要删除的地址是否是默认地址
        UserAddresses addressToDelete = userAddressesMapper.selectOne(
                new QueryWrapper<UserAddresses>()
                        .eq("user_id", userId)
                        .eq("id", id)
                        .eq("is_default", 1)
        );

        if (addressToDelete != null) {
            userLogService.logDeleteAddressAction(userId, "默认地址不能删除", 0, "默认地址不能删除,请先重新选择默认地址后删除");
            throw new ZsdException("默认地址不能删除,请先重新选择默认地址后删除", 1010);
        }

        // 删除地址信息
        int rowsAffected = userAddressesMapper.deleteById(id);
        if (rowsAffected == 0) {
            userLogService.logDeleteAddressAction(userId, "地址不存在或已删除", 0, "地址不存在或已删除");
            throw new ZsdException("地址不存在或已删除", 1011);
        }

        userLogService.logDeleteAddressAction(userId, "用户删除地址信息成功", 1, null);
        return true;
    }

    @Override
    public Result<String> setDefaultAddress(String userId, int id) throws Exception {
        // 先查看是否有默认地址
        QueryWrapper<UserAddresses> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("is_default", 1);
        int defaultCount = Math.toIntExact(userAddressesMapper.selectCount(queryWrapper));

        if (defaultCount > 0) {
            // 如果有默认地址，则将对应的默认地址的is_default字段设置为0
            UpdateWrapper<UserAddresses> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", userId).eq("is_default", 1);
            userAddressesMapper.update(null, updateWrapper.set("is_default", 0));
        }

        // 将当前地址的is_default字段设置为1
        UpdateWrapper<UserAddresses> updateCurrentWrapper = new UpdateWrapper<>();
        updateCurrentWrapper.eq("id", id);
        userAddressesMapper.update(null, updateCurrentWrapper.set("is_default", 1));

        return null;
    }


}
